package com.firewolf.rbac.verifycode;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作者：刘兴
 * 时间:19/3/6
 **/
@Component
public class ImageCodeVerifyFilter extends OncePerRequestFilter {


    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (StringUtils.equals("/login", request.getRequestURI()) && StringUtils.equalsIgnoreCase(request.getMethod(), "post")) { //如果是登录请求，就校验验证码
            try {
                validate(request);
            } catch (AuthenticationException e) {
                //验证码验证失败，交给错误处理器
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) throws ServletRequestBindingException, AuthenticationException {
        String imagecode = ServletRequestUtils.getStringParameter(request, "verifycode");
        if (StringUtils.isBlank(imagecode))
            throw new ImageCodeException("verify code is null ");

        ImageCode imagecodInSession = (ImageCode) request.getSession().getAttribute(VerifyCodeController.SESSION_KEY);
        if (imagecodInSession == null)
            throw new ImageCodeException("there is no verify code ");

        if (!imagecodInSession.isEffective()) {
            request.getSession().removeAttribute(VerifyCodeController.SESSION_KEY);
            throw new ImageCodeException("verify code is timeout !");
        }
        if (!StringUtils.equalsIgnoreCase(imagecodInSession.getCode(), imagecode)) {
            throw new ImageCodeException("verify code is error");
        }
        request.getSession().removeAttribute(VerifyCodeController.SESSION_KEY);
    }
}
